<?php

namespace App\Repositories\Order;

use App\Criteria\OrderInfo\GetByUserIdCriteria;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use League\Flysystem\Config;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Models\Order\OrderInfo;
use App\Validators\Order\OrderInfoValidator;

/**
 * Class OrderInfoRepositoryEloquent
 * @package namespace App\Repositories\Order;
 */
class OrderInfoRepositoryEloquent extends BaseRepository implements OrderInfoRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return OrderInfo::class;
    }

    /**
    * Specify Validator class name
    *
    * @return mixed
    */
    public function validator()
    {

        return OrderInfoValidator::class;
    }


    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

    /**
     * 获取指定商品指定时间内所购买的商品总数
     * @author Jerry
     * @param int $goodsId
     * @param $startTime
     * @param $endTime
     * @return mixed
     */
    public function findGoodsPromoteOrderNumber(int $goodsId, $startTime, $endTime)
    {

        $order = DB::table('order_info')
            ->leftJoin('order_goods', 'order_info.order_id', '=', 'order_goods.order_id')
            ->where([
                ['order_goods.goods_id', '=', $goodsId],
                ['order_info.add_time', '<', $endTime],
                ['order_info.add_time', '>=', $startTime],
                ['order_info.pay_status', '<>', 0],
                ['order_info.shipping_status', '<>', 2],
                ['order_info.shipping_status', '<>', 3],
            ])
            ->sum('order_goods.goods_number');

        return $order;
    }

    /**
     * 更新订单状态(order_status)
     * @param $order_id 订单ID;
     * @param $order_status 订单状态;
     * @return bool|mixed 设置是否成功标识|更新模型对象;
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     * @author ^2_3^岑业宝
     */
    public function updateOrderStatus($order_id, $order_status) {
        $flag = false;

        /// 订单模型
        $m_order_o = $this->find($order_id);
        if( !$m_order_o ) {
            return $flag;
        }

        /// 状态相同不处理
        if( $m_order_o->order_status == $order_status ) {
            return true;
        }

        /// 更新订单状态
        $m_order_u = $this->update(["order_status"=>$order_status], $order_id);
        if( $m_order_u ) {
            $m_order_u->order_status_old = $m_order_o->order_status;
            return $m_order_u;
        }

        return $flag;
    }

    /**
     * 更新支付状态(pay_status)
     * @param $order_id 订单ID;
     * @param $pay_status 支付状态;
     * @return bool|mixed 设置是否成功标识|模型对象;
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     * @author ^2_3^岑业宝
     */
    public function updatePayStatus($order_id, $pay_status) {
        $flag = false;

        /// 订单模型
        $m_pay_o = $this->find($order_id);
        if( !$m_pay_o ) {
            return $flag;
        }

        /// 状态相同不处理
        if( $m_pay_o->pay_status == $pay_status ) {
            return true;
        }

        /// 更新支付状态
        $m_pay_u = $this->update(["pay_status"=>$pay_status], $order_id);
        if( $m_pay_u ) {
            $m_pay_u->pay_status_old = $m_pay_o->pay_status;
            return $m_pay_u;
        }

        return $flag;
    }

    /**
     * 更新发货状态(shipping_status)
     * @param $order_id 订单ID;
     * @param $shipping_status 发货状态;
     * @return bool|mixed 设置是否成功标识|模型对象;
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     * @author ^2_3^岑业宝
     */
    public function updateShippingStatus($order_id, $shipping_status) {
        $flag = false;

        /// 订单模型
        $m_ship_o = $this->find($order_id);
        if( !$m_ship_o ) {
            return $flag;
        }

        /// 状态相同不处理
        if( $m_ship_o->shipping_status == $shipping_status ) {
            return true;
        }

        /// 更新发货状态
        $m_ship_u = $this->update(["shipping_status"=>$shipping_status], $order_id);
        if( $m_ship_u ) {
            $m_ship_u->shipping_status_old = $m_ship_o->shipping_status;
            return $m_ship_u;
        }

        return $flag;
    }

    /**
     * 获取所有订单
     * @author yangzhic
     * @param int $page_size
     * @param array $columns
     * @return mixed
     */
    public function getAll(int $page_size,array $columns=['*']){
        return $this->orderBy('order_id','desc')->paginate($page_size,$columns);
    }

    /**
     * 获取订单信息
     * @param int $orderId
     * @param array $columns
     * @return mixed
     */
    public function getOrderInfoById(int $orderId,array $columns=['*']){
        return $this->find($orderId,$columns);
//        return $this->findWhere(['order_id'=>$orderId],$columns);
    }

    /**
     * 获取订单信息
     * @author yangzhic
     * @param int $orderId
     * @param array $columns
     * @return mixed
     */
    public function getOrderById(int $orderId,array $columns=['*']){
        return $this->findWhere(['order_id'=>$orderId],$columns);
    }

    /**
     * 获取用户订单
     * @author yangzhic
     * @param int $userId
     * @param int $page_size
     * @param array $columns
     * @return mixed
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function getOrdersByUserId(int $userId,int $page_size,array $columns=['*']){
        //设置查询条件
        $this->pushCriteria(new GetByUserIdCriteria($userId));
        //返回查询结果，带分页
        return $this->paginate($page_size,$columns);
    }

    /**
     * 新增订单信息
     * @author yangzhic
     * @param $order
     * @return int
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function saveOrder($order){
        return DB::table($this->makeModel()->getTable())->insertGetId($order);
    }

    /**
     * 获取订单信息表字段
     * @author yangzhic
     * @return array
     * @throws \Prettus\Repository\Exceptions\RepositoryException
     */
    public function getOrderInfoColumns(){
        $columns = Schema::getColumnListing($this->makeModel()->getTable());
        return $columns;
    }


    public function get38data(){
        $order_list = DB::table('order_goods as og')
            ->leftJoin('order_info as oi','og.order_id','=','oi.order_id')
            ->where('og.goods_id','=','18990')
            ->select(['oi.order_id','oi.user_id'])
            ->get();

//        return $order_list;

        $data = ['total'=>0,'new'=>0,'old'=>0,'new_user'=>[],'old_user'=>[]];
        foreach($order_list as $key=>$val){
            $check_buy_again = $this->check_buy_again($val->user_id,$val->order_id);
            if($check_buy_again){
                $data['total']+=1;
                $check_new_user = $this->check_new_user($val->user_id,$val->order_id);
                if($check_new_user){
                    $data['new_user'][] = $val->user_id;
                    $data['new']+=1;
                }else{
                    $data['old_user'][] = $val->user_id;
                    $data['old']+=1;
                }
            }
        }

        return $data;
    }

    public function check_new_user($uid,$orderId){
        $flag = true;
        $count = DB::table('order_info')
            ->where('user_id','=',$uid)
            ->where('order_id','<',$orderId)
            ->count('order_id');

        if($count>0){
            $flag = false;
        }

        return $flag;
    }

    public function check_buy_again($uid,$orderId){
        $flag = false;
        $count = DB::table('order_info')
            ->where('user_id','=',$uid)
            ->where('order_id','>',$orderId)
            ->count('order_id');

        if($count>0){
            $flag = true;
        }

        return $flag;
    }

    /**
     *   检查订单未确认、未付款、未配送的取消订单释放符合条件
     */
    public function CheckOrderCancelEligible($order_id){
       //TIMESTAMPDIFF(MINUTE,CONVERT_TZ(FROM_UNIXTIME(IF(t.pay_start_time=0,t.add_time,t.pay_start_time)),'+00:00','+08:00'),NOW())>
        if(empty($order_id)){
            return false;
        }
        $field = [
            'order_id'
        ];
        $exec_time=gm_time()-config('shidexian.auto_order_cancel_time')*60;
        $where=[
            ['order_id','=',$order_id],
            ['order_status','=',config('custom.order_status_0')],
            ['pay_status','=',config('custom.pay_status_0')],
            ['shipping_status','=',config('custom.shipping_status_0')],
        ];
        //DB::enableQueryLog();
        $data = $this->model
            ->where($where)
            ->whereRaw('IF(pay_start_time=0,add_time,pay_start_time) < ?',[$exec_time])
            ->addSelect($field)
           ->first();
        $returndata = collect($data)->toArray();
        if(count($returndata)>0){ //此订单不在有效时间
           return true;
        }else{
            return false;
        }
        //dd(DB::getQueryLog());
    }

    public function CheckUsersOrderCancelEligible($order_id,$user_id){
        if(empty($order_id)){
            return false;
        }
        $field = [
            'order_id'
        ];
        $where=[
            ['order_id','=',$order_id],
            ['user_id','=',$user_id],
            ['order_status','=',config('custom.order_status_0')],
            ['pay_status','=',config('custom.pay_status_0')],
            ['shipping_status','=',config('custom.shipping_status_0')],
        ];
        $orwhere=[
            ['order_id','=',$order_id],
            ['user_id','=',$user_id],
            ['order_status','=',config('custom.order_status_1')],
            ['pay_status','=',config('custom.pay_status_2')],
            ['shipping_status','=',config('custom.shipping_status_0')],
        ];
        $data = $this->model
            ->where($where)
            ->orWhere($orwhere)
            ->addSelect($field)
            ->first();
        $returndata = collect($data)->toArray();
        if(count($returndata)>0){
            return true;
        }else{
            return false;
        }
    }

    /**
    *  更新取消订单状态以及订单支付备注
     */
    public function UpdateOrderStatusAndPayNote($order_id){
        if(empty($order_id)){
            return false;
        }
        $exec_time=gm_time()-config('shidexian.auto_order_cancel_time')*60;
        $where=[
            ['order_id','=',$order_id],
            ['order_status','=',config('custom.order_status_0')],
            ['pay_status','=',config('custom.pay_status_0')],
            ['shipping_status','=',config('custom.shipping_status_0')],
        ];
        $updata=[
            'order_status'=>config('custom.order_status_2'),
            'pay_note'=>'支付超时自动取消'
        ];
        $upid=$this->model
                ->where($where)
                ->whereRaw('IF(pay_start_time=0,add_time,pay_start_time) < ?',[$exec_time])
                ->update($updata);
        if($upid){
            return true;
        }else{
            return false;
        }
    }

    /***
     * 用户手动取消订单
     * @param $order_id
     * @param $user_id
    @author echa
     * @return bool
     */
    public function UpdateUsersOrderStatusAndPayNote($order_id,$user_id){
        if(empty($order_id) || empty($user_id)){
            return false;
        }
        $where=[
            ['order_id','=',$order_id],
            ['user_id','=',$user_id],
            ['order_status','=',config('custom.order_status_0')],
            ['pay_status','=',config('custom.pay_status_0')],
            ['shipping_status','=',config('custom.shipping_status_0')],
        ];
        $updata=[
            'order_status'=>config('custom.order_status_2'),
            'pay_note'=>'用户手动取消订单'
        ];
        $upid=$this->model->where($where)->update($updata);
        if($upid){
            return true;
        }else{
            return false;
        }
    }


    public function UpdateOrderCancelInitialize($order_id,$user_id=0){
        $pay_note='';
        if($user_id!=0){
            $pay_note='用户手动取消订单';
        }else{
            $pay_note='支付超时自动取消';
        }
        $where=[
            ['order_status','=',config('custom.order_status_2')],
            ['pay_status','=',config('custom.pay_status_0')],
            ['pay_note','=',$pay_note],
            ['order_id','=',$order_id]
        ];
        $updata=[
            'to_buyer'=>$pay_note,
            'pay_note'=>'',
            'money_paid'=>0,
            'order_amount'=>0,
            'surplus'=>0
        ];
        $upid=$this->model
            ->where($where)
            ->update($updata);
        if($upid){
            return true;
        }else{
            return false;
        }
    }

    public function DeleteActivityQuota($order_id){
        $order_info=$this->getOrderInfoById($order_id,['order_status']);
        if($order_info->order_status==config('custom.order_status_2')){
            $where=[
                ['order_id','=',$order_id]
            ];
            $deid=DB::table('activity_quota')->where($where)->delete();
            if($deid){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }


    public function OperationBonusfreight($order_id,$user_id=0){
        $to_buyer='';
        if($user_id!=0){
            $to_buyer='用户手动取消订单';
        }else{
            $to_buyer='支付超时自动取消';
        }
        $where=[
            ['order_status','=',config('custom.order_status_2')],
            ['bonus_freight_id','!=',0],
            ['pay_status','=',config('custom.pay_status_2')],
            ['to_buyer','=',$to_buyer],
            ['order_id','=',$order_id]
        ];
        $bonus_freight_id=$this->model->where($where)->value('bonus_freight_id');
        $this->model->where($where)->update(['bonus_freight_id'=>0]);
        if($bonus_freight_id){
            $updata=[
                'used_time'=>0,
                'order_id'=>0,
                'pay_log_id'=>0
            ];
            DB::table('user_bonus')->where([['bonus_id','=',$bonus_freight_id]])->update($updata);
        }
        return true;
    }

    /*
     * 更新用户奖金
     * */
    public function UpdateUsedTimeAndOrder($order_id,$user_id=0){
        $pay_note='';
        if($user_id!=0){
            $pay_note='用户手动取消订单';
        }else{
            $pay_note='支付超时自动取消';
        }
        $where=[
            ['order_info.bonus_id','!=',0],
            ['order_info.order_status','=',config('custom.order_status_2')],
            ['order_info.pay_status','=',config('custom.pay_status_0')],
            ['order_info.pay_note','=',$pay_note],
            ['order_info.order_id','=',$order_id]
        ];
        $updata=[
            'user_bonus.used_time'=>0,
            'user_bonus.order_id'=>0
        ];
        $upid=DB::table('user_bonus')
            ->join('order_info','user_bonus.order_id','=','order_info.order_id')
            ->where($where)
            ->update($updata);
        if($upid){
            return true;
        }else{
            return false;
        }
    }

    /***
     * 订单绑定金蝶发货通知单编号
     * @param $order_id
     * @param $cn_sn
    @author echa
     */
    public function UpdateOrderk3cn_sn($order_id,$cn_sn){
        $upid=$this->model->where([['order_id','=',$order_id]])->update(["k3cn_sn"=>$cn_sn]);
        if($upid){
            return true;
        }else{
            return false;
        }
    }



}
